package com.thinkis.modules.sys.security;

import java.util.ArrayList;
import java.util.Collection;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

import com.thinkis.modules.sys.oauth.OauthRealm;

/**
 * @author liuzhiping
 * 自定义Authenticator
 * 注意，不同的token使用不同的realm。
 *
 */
public class CustomizedModularRealmAuthenticator extends ModularRealmAuthenticator {

	@Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken)
            throws AuthenticationException {
        // 判断getRealms()是否返回为空
        assertRealmsConfigured();
        
        // 所有Realm
        Collection<Realm> realms = getRealms();
        // 登录类型对应的所有Realm
        Collection<Realm> typeRealms = new ArrayList<>();
        for (Realm realm : realms) {
        	 if(authenticationToken instanceof UsernamePasswordToken){
        		 if (realm instanceof SystemAuthorizingRealm)
                     typeRealms.add(realm);
             }else{
            	 if (realm instanceof OauthRealm)
                     typeRealms.add(realm);
             }
        }

        // 判断是单Realm还是多Realm
        if (typeRealms.size() == 1)
            return doSingleRealmAuthentication(typeRealms.iterator().next(), authenticationToken);
        else
            return doMultiRealmAuthentication(typeRealms, authenticationToken);
    }

}
